package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test7 {
    public static void t1(){
        long startTime=System.currentTimeMillis();
        User user=new User();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        long endTime=System.currentTimeMillis();
        System.out.println("普通方法执行10亿次getName:"+(endTime-startTime)+"ms");
    }

    public static void t2() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        long startTime=System.currentTimeMillis();
        User user=new User();
        Class c = Class.forName("reflection.User");
//        Constructor constructor = c.getDeclaredConstructor();
//        User user= (User) constructor.newInstance();
        Method getName = c.getDeclaredMethod("getName", null);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("反射执行10亿次getName:"+(endTime-startTime)+"ms");
    }

    public static void t3() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        long startTime=System.currentTimeMillis();
        User user=new User();
        Class c = Class.forName("reflection.User");
//        Constructor constructor = c.getDeclaredConstructor();
//        User user= (User) constructor.newInstance();
        Method getName = c.getDeclaredMethod("getName", null);
        getName.setAccessible(true);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }
        long endTime=System.currentTimeMillis();
        System.out.println("反射关闭监测，执行10亿次getName:"+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        t1();
        t2();
        t3();
    }
}
